package com.example.spider.provider.m3u8.dto;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * https://zhuanlan.zhihu.com/p/501829443
 */
@Getter
@Setter
@Accessors(chain = true)
public class M3u8MetaInfo {

    String url;

    String sourceContent;

    String name;

    Map<String, M3u8Key> keyMap;

    List<M3u8TsPart> tsPart;

    /**
     * 一个m3u8可能包含多个子m3u8，for client 多码率适配，一般有 sub，则无 tsPart
     */
    List<M3u8MetaInfo> subMetaInfo;

    String version;

    boolean independentSegments;

    ClientStartInfo start;

    Map<String, Object> define;

    int mediaSequence = 0;

    Map<String, Object> streamInf;

    Map<String, Object> iframeStreamInf;

    Map<String, String> extStreamInf;

    Map<String, Object> sessionData;

    /**
     * 其属性列表与 EXT-X-KEY 相同，除了 METHOD 属性的值必须不为NONE
     */
    Map<String, Object> sessionKey;

    String defaultDuration;

    String type = "VOD";

    public synchronized M3u8Key getOrPut(M3u8Key m3u8Key) {
        String key = m3u8Key.getUri() != null ? m3u8Key.getUri() : "NONE";
        M3u8Key old = null;
        if (keyMap == null) {
            keyMap = new HashMap<>();
        }
        if ((old = keyMap.get(key)) != null) {
            return old;
        }
        keyMap.put(key, m3u8Key);
        return null;
    }

    public synchronized M3u8MetaInfo addTsPart(M3u8TsPart part) {
        if (tsPart == null) {
            tsPart = new ArrayList<>(200);
        }
        tsPart.add(part);
        return this;
    }

    public synchronized M3u8MetaInfo addSubM3u8MetaInfo(M3u8MetaInfo sub) {
        if (subMetaInfo == null) {
            subMetaInfo = new ArrayList<>(5);
        }
        subMetaInfo.add(sub);
        return this;
    }
}
